package Demo4;

class Counter {
    public int count = 0;
    public String locker = "hello";

     //使用 synchronized 修饰普通方法
    public synchronized void add() {
        count++;
        System.out.println(Thread.currentThread().getName() + " 计数: " + count);
    }

    // 第二种写法
    public void add2() {
        synchronized (this) {
            count++;
            System.out.println(Thread.currentThread().getName() + " 计数: " + count);
        }
    }

    // 第三种写法
    public void add3() {
       synchronized (locker) {
           count++;
           System.out.println(Thread.currentThread().getName() + " 计数: " + count);
       }
    }
}

public class Demo4 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        // 创建两个线程来调用 increment 方法
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                counter.add();
            }
        }, "线程1");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                counter.add();
            }
        }, "线程2");

        // 启动线程
        t1.start();
        t2.start();

        // 等待两个线程执行完毕
        t1.join();
        t2.join();

        System.out.println("最终计数: " + counter.count);
    }
}